<template>
  <div class="w-full">
    <div class="min-w-[240px] overflow-y-auto" v-if="mode === 'list'">
      <a-input-search
        class="mb-2"
        :placeholder="t['请输入门店名称']"
        allowClear
        v-model="query.storeName"
        @search="search"
        @keydown.enter="search"
      ></a-input-search>
      <x-table
        @getList="getList"
        @search="search"
        :columns="translateColumns(columns)"
        :table="table"
        :query="query"
        @select="onSelect"
        has-extra-data
      ></x-table>
    </div>

    <a-select
      @change="onSelect"
      v-else-if="mode === 'select'"
      :options="storeList"
      allowClear
      v-model="selected"
    >
    </a-select>
  </div>
</template>

<script setup lang="ts">
import { fetchStoreData, storeList } from "@/api/selector/selector";
import { listStore } from "@/api/service/store/store";
import { IStore } from "@/api/service/store/types";
import { userStore } from "@/store/modules/user/user";

const t = translate("公共模块");
const selected = defineModel<string>();
const emit = defineEmits(["change"]);
const store = userStore();
const query = useQuery<IStore>({
  pageSize: 10,
  pageNum: 1
});
const table = useTable<IStore>({
  rowKey: "id"
});
const props = withDefaults(
  defineProps<{
    mode?: "select" | "list";
    allowSelectSelf?: boolean;
  }>(),
  {
    multiple: false,
    mode: "select",
    allowSelectSelf: true
  }
);
const search = () => {
  query.value.pageNum = 1;
  getList();
};
const getList = async () => {
  table.value.data = [];
  const data = await listStore(query.value);
  query.value.pageSize = 10;
  data.rows.unshift({
    id: store.user.deptId,
    storeName: t.value["本门店"],
    storeManager: store.user.userName,
    storeNo: store.user.storeNo || ""
  });
  table.value.data = data.rows;
  query.value.total = data.total;
};
const columns = [
  { title: "门店名称", dataIndex: "storeName" },
  { title: "门店管理者", dataIndex: "storeManager" },
  { title: "编码", dataIndex: "storeNo" }
];

const onSelect = (data: any) => {
  if (props.mode === "list") {
    selected.value = data.rowKey;
  }
  emit("change", data);
};

onMounted(() => {
  if (props.mode === "list") {
    getList();
  } else {
    fetchStoreData();
  }
});
</script>

<style lang="scss" scoped>
.active {
  background: var(--primary) !important;
  color: white !important;
}

.store-item {
  border: 1px solid #a8a8a8;
  @apply px-4 py-2 text-center cursor-pointer  hover:bg-slate-100;
}
</style>
